package com.zy.openchat.core.manager;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zy.openchat.App;
import com.ja.openchat.R;
import com.zy.openchat.core.model.group.SuperGroupInfo;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatExCacheManager {
    private volatile static ChatExCacheManager cacheManager;
    private Map<Long, ChatExInfo> chatExCacheMap = new HashMap<>();
    private Map<String, Integer> defaultBgMap = new HashMap<>();

    //会话全局设置id，全局背景设置时，代替参数:chatid
    public static final long CHAT_GLOBAL_ID = -1;

    private ChatExCacheManager() {
        load();
    }

    public static ChatExCacheManager getChatExCacheManager() {
        if (cacheManager == null) {
            synchronized (ChatExCacheManager.class) {
                if (cacheManager == null) {
                    cacheManager = new ChatExCacheManager();
                }
            }
        }
        return cacheManager;
    }

    public static void reset() {
        cacheManager = null;
    }

    private void load() {
        defaultBgMap.put("chat_bg_1", R.mipmap.chat_bg_1);
        defaultBgMap.put("chat_bg_2", R.mipmap.chat_bg_2);
        defaultBgMap.put("chat_bg_3", R.mipmap.chat_bg_3);
        defaultBgMap.put("chat_bg_4", R.mipmap.chat_bg_4);
        defaultBgMap.put("chat_bg_5", R.mipmap.chat_bg_5);
        defaultBgMap.put("chat_bg_6", R.mipmap.chat_bg_6);
        defaultBgMap.put("chat_bg_7", R.mipmap.chat_bg_7);

        Map<Long, ChatExInfo> map = getChatExCacheMap();
        if (map != null && map.size() > 0) {
            chatExCacheMap = map;
        }
    }

    public int getGroupMemberCount(long chatId, SuperGroupInfo group) {
        if (group != null && group.member_count > 0) {
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null) {
                info.groupMemberCount = group.member_count;
            } else {
                info = new ChatExInfo();
                info.chatId = chatId;
                info.groupMemberCount = group.member_count;
                chatExCacheMap.put(chatId, info);
            }
            //保存
            saveChatExCacheMap(chatExCacheMap);
            //返回
            return info.groupMemberCount;
        } else {
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null) {
                return info.groupMemberCount;
            }
            return 0;
        }
    }

    //聊天背景图片相关

    /**
     * app内置会话背景列表，返回类型：String，图片来自mipmap目录，返回为图片资源key值
     *
     * @return 默认图片列表
     */
    public static List<String> defaultChatBgList() {
        String[] list = {"chat_bg_1", "chat_bg_2", "chat_bg_3", "chat_bg_4", "chat_bg_5", "chat_bg_6", "chat_bg_7"};
        return new ArrayList<String>(Arrays.asList(list));
    }

    /**
     * 设置会话背景
     *
     * @param chatId 会话id
     * @param chatBg chatBg可以是一个路径，可以是mipmap对应的key
     */
    public void setChatBg(long chatId, String chatBg) {
        ChatExInfo info = chatExCacheMap.get(chatId);
        if (info != null) {
            info.chatBg = chatBg;
        } else {
            info = new ChatExInfo();
            info.chatId = chatId;
            info.chatBg = chatBg;
            chatExCacheMap.put(chatId, info);
        }
        //保存
        saveChatExCacheMap(chatExCacheMap);
        //发送通知
        EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Chat_Bg_Changed, chatId));
    }

    /**
     * 清空聊天背景
     *
     * @param chatId 会话id
     */
    public void cleanChatBgWithChatId(long chatId) {
        ChatExInfo info = chatExCacheMap.get(chatId);
        if (info != null) {
            info.chatBg = null;
            //保存
            saveChatExCacheMap(chatExCacheMap);
            //发送通知
            EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Chat_Bg_Changed, chatId));
        }
    }

    /**
     * 所有聊天窗口应用全局背景
     */
    public void applyGlobalBgToAllChatView() {
        if (chatBg(CHAT_GLOBAL_ID) != null) {
            //前提是，已经设置了全局背景
            List<ChatExInfo> list = new ArrayList<ChatExInfo>(chatExCacheMap.values());
            for (ChatExInfo set : list) {
                if (set.chatId != CHAT_GLOBAL_ID) {
                    set.chatBg = null;
                }
            }
            //保存
            saveChatExCacheMap(chatExCacheMap);
        }
    }

    /**
     * 获取会话背景 - 本地文件
     *
     * @param chatId 会话id
     * @return
     */
    public String chatLocalFileBg(long chatId) {
        if (chatId == CHAT_GLOBAL_ID) {
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null) {
                return info.chatBg;
            }
            return null;
        } else {
            //优先当前会话设置
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null && info.chatBg != null) {
                return info.chatBg;
            }
            //然后全局设置
            info = chatExCacheMap.get(CHAT_GLOBAL_ID);
            if (info != null) {
                return info.chatBg;
            }
            return null;
        }
    }

    /**
     * 获取会话背景 - 本地资源文件
     *
     * @param chatId 会话id
     * @return
     */
    public int chatMipmapBg(long chatId) {
        if (chatId == CHAT_GLOBAL_ID) {
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null) {
                Integer sid = defaultBgMap.get(info.chatBg);
                return sid != null ? sid : 0;
            }
            return 0;
        } else {
            //优先当前会话设置
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null && info.chatBg != null) {
                Integer sid = defaultBgMap.get(info.chatBg);
                return sid != null ? sid : 0;
            }
            //然后全局设置
            info = chatExCacheMap.get(CHAT_GLOBAL_ID);
            if (info != null) {
                Integer sid = defaultBgMap.get(info.chatBg);
                return sid != null ? sid : 0;
            }
            return 0;
        }
    }

    private ChatExInfo chatBg(long chatId) {
        if (chatId == CHAT_GLOBAL_ID) {
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null) {
                return info;
            }
            return null;
        } else {
            //优先当前会话设置
            ChatExInfo info = chatExCacheMap.get(chatId);
            if (info != null && info.chatBg != null) {
                return info;
            }
            //然后全局设置
            info = chatExCacheMap.get(CHAT_GLOBAL_ID);
            if (info != null) {
                return info;
            }
            return null;
        }
    }

    /**
     * 是否本地资源文件背景
     *
     * @param chatId 会话id
     * @return
     */
    public boolean chatBgIsFromMipmap(long chatId) {
        ChatExInfo info = chatBg(chatId);
        if (info != null && !StringUtils.isEmpty(info.chatBg)) {
            return info.chatBg.startsWith("chat_bg_");
        }
        return false;
    }

    /**
     * 是否本地文件背景
     *
     * @param chatId 会话id
     * @return
     */
    public boolean chatBgIsFromLocalFile(long chatId) {
        ChatExInfo info = chatBg(chatId);
        if (info != null && !StringUtils.isEmpty(info.chatBg)) {
            return !info.chatBg.startsWith("chat_bg_");
        }
        return false;
    }

    //本地缓存
    private Map<Long, ChatExInfo> getChatExCacheMap() {
        if (AuthUserManager.getAuthUserManager().currentAuthUser() != null) {
            Context context = App.getInstanse();
            String jsonStr = context.getSharedPreferences("ChatExCache", Context.MODE_PRIVATE).getString(AuthUserManager.getAuthUserManager().currentAuthUser().data_directory, null);
            if (jsonStr != null) {
                Type mapType = new TypeToken<Map<Long, ChatExInfo>>() {
                }.getType();
                return new Gson().fromJson(jsonStr, mapType);
            }
        }
        return null;
    }

    private void saveChatExCacheMap(Map<Long, ChatExInfo> chatsMap) {
        if (AuthUserManager.getAuthUserManager().currentAuthUser() != null) {
            if (chatsMap == null) {
                return;
            }
            String jsonStr = new Gson().toJson(chatsMap);
            Context context = App.getInstanse();
            SharedPreferences.Editor editor = context.getSharedPreferences("ChatExCache", Context.MODE_PRIVATE).edit();
            editor.putString(AuthUserManager.getAuthUserManager().currentAuthUser().data_directory, jsonStr);
            editor.apply();
        }
    }
}
